package com.hs.communication.common.config;

import com.hs.common.core.constant.CacheConstants;
import com.hs.common.core.constant.SecurityConstants;
import com.hs.common.redis.service.RedisService;
import com.hs.communication.common.entity.Charger;
import com.hs.communication.common.feign.RemoteChargerService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 实际项目中,定时任务应该单独一个微服务,因为更新的是所有服务实例的redis
 */
@Component
public class HeartbeatCheckTask {

    @Resource
    private RedisService redisService;

    @Resource
    private RemoteChargerService remoteChargerService;

    private static final long HEARTBEAT_TIMEOUT_MINUTES = 2; // 超时时间设定为2分钟，根据实际情况调整

    @Scheduled(fixedDelay = 2, timeUnit = TimeUnit.MINUTES) // 每隔60秒执行一次定时任务
    public void checkHeartbeats() {
        System.out.println("定时检查离线状态");
        LocalDateTime currentTimestamp = LocalDateTime.now().minus(HEARTBEAT_TIMEOUT_MINUTES, ChronoUnit.MINUTES);

        Map<String, String> map = redisService.getCacheMap(CacheConstants.DEVICE_HEARTBEAT_TIME_KEY);
        System.out.println("map.size=" + map.size());
        map.forEach((key, value) -> {
            LocalDateTime dateTime = LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.out.println("key=" + key);
            System.out.println("value=" + dateTime);
            //心跳超时+最新上报时间 < 当前时间,心跳超时,更改为离线状态
            if (currentTimestamp.isAfter(dateTime)) {
                System.out.println("设备离线,sn=" + key);
                Charger charger = Charger.builder().sn(key).status("0").offOnlineTime(dateTime).build();
                //更改数据库在线/离线状态和时间
                remoteChargerService.updateStatus(charger, SecurityConstants.INNER);
            }
        });
    }
}
